package com.example.administrator.hqq.activity.home;

import android.app.AlertDialog;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.TextView;

import com.blankj.utilcode.util.SPUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.example.administrator.hqq.R;
import com.example.administrator.hqq.View.alertview.AlertViewFactory;
import com.example.administrator.hqq.activity.complain.ChatComplainActivity;
import com.example.administrator.hqq.adapter.group.KickGroupListAdapter;
import com.example.administrator.hqq.base.MyActivity;
import com.example.administrator.hqq.bean.Complain;
import com.example.administrator.hqq.bean.group.GetGroupSettingsBean;
import com.example.administrator.hqq.config.LoongsConfig;
import com.example.administrator.hqq.config.UrlFactory;
import com.example.administrator.hqq.utils.HintWordsUtils;
import com.zhy.autolayout.AutoRelativeLayout;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import io.rong.push.RongPushClient;
import okhttp3.Call;

public class KickMemberActivity extends MyActivity {

    @BindView(R.id.return_auto)
    AutoRelativeLayout returnAuto;
    @BindView(R.id.title)
    TextView title;
    @BindView(R.id.report_auto)
    AutoRelativeLayout reportAuto;
    @BindView(R.id.list)
    ListView list;
    private boolean aBoolean=true;
    private List<GetGroupSettingsBean.DataBean.MemberBean> lists;
    private String TAG = this.getClass().getSimpleName();
    private KickGroupListAdapter kickGroupListAdapter;
    private List<String> strings;
    private AlertDialog alertDialog;
    private int index=-1;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_kick_member);
        ButterKnife.bind(this);
        EventBus.getDefault().register(this);
        initview();
    }

    private void initview() {
        strings = new ArrayList<>();
        lists = (List<GetGroupSettingsBean.DataBean.MemberBean>) getIntent().getSerializableExtra(LoongsConfig.member);
        title.setText("聊天成员(" + lists.size() + ")");
        kickGroupListAdapter = new KickGroupListAdapter(this, lists);
        kickGroupListAdapter.setGroup_owner(LoongsConfig.getUser_id());
        list.setAdapter(kickGroupListAdapter);
        list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, final int i, long l) {
                if (!lists.get(i).getId().equals(LoongsConfig.getUser_id()))
                {
                    strings.clear();
                    String[] stringArray = getResources().getStringArray(R.array.delete_cause);
                    for (String s : stringArray) {
                        strings.add(s);
                    }
                    alertDialog = AlertViewFactory.getInstance().showDeleteFriendReport(KickMemberActivity.this,"评价该用户","其他严重违法情形,请前往投诉", strings, new AlertViewFactory.DeleteFriendReportOnclicke() {
                        @Override
                        public void submit(int position) {
                            GroupMemberReport(i, position);
                            deleteMember(i);
                            alertDialog.cancel();
                        }
                        @Override
                        public void goComplain(int position) {
                            index=i;
                            alertDialog.cancel();
                            ChatComplainActivity.start(KickMemberActivity.this
                                    , RongPushClient.ConversationType.GROUP.toString()
                                    , getIntent().getStringExtra(LoongsConfig.group_id)
                                    , lists.get(i).getId()
                                    , LoongsConfig.ComplainType.GROUP_MEMBER.toString());
                        }
                    });
                }
            }
        });
    }

    /**
     * 群成员举报
     * @param i
     * @param position
     */
    private void GroupMemberReport(int i, int position) {
        OkHttpUtils.get().url(UrlFactory.ReportForum())
                .addParams(LoongsConfig.id,lists.get(i).getId())
                .addParams(LoongsConfig.user_id, SPUtils.getInstance().getString(LoongsConfig.user_id))
                .addParams(LoongsConfig.reason_id,position+501+"")
                .addParams(LoongsConfig.type,"4")
                .addParams(LoongsConfig.group_id,getIntent().getStringExtra(LoongsConfig.group_id))
                .build().execute(new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
                Log.e(TAG, "onError: "+e );
            }

            @Override
            public void onResponse(String response, int id) {
                Log.e(TAG, "onResponse: "+response );
                try {
                    JSONObject jsonObject = new JSONObject(response);
                    HintWordsUtils.showMarkeWords(jsonObject.getInt(LoongsConfig.code), jsonObject.getString(LoongsConfig.description));
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
    }

    private void deleteMember(final int i) {
        aBoolean=false;
        OkHttpUtils.get().url(UrlFactory.setPassiveExit())
                .addParams(LoongsConfig.group_id, getIntent().getStringExtra(LoongsConfig.group_id))
                .addParams(LoongsConfig.owner_id, LoongsConfig.getUser_id())
                .addParams(LoongsConfig.target_user_id, lists.get(i).getId())
                .build().execute(new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
                Log.e(TAG, "onError: " + e);
            }

            @Override
            public void onResponse(String response, int id) {
                Log.e(TAG, "onResponse: " + response);
                try {
                    JSONObject jsonObject = new JSONObject(response);
                    if (jsonObject.getInt(LoongsConfig.code) == 200) {
                        ToastUtils.showShort("踢出成功");
                        lists.remove(i);
                        title.setText("聊天成员(" + lists.size() + ")");
                        kickGroupListAdapter.notifyDataSetChanged();
                        Complain complain = new Complain(Complain.Type.KICK_MEMBER, "");
                        EventBus.getDefault().post(complain);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
    }

    @OnClick(R.id.return_auto)
    public void onViewClicked() {
        Intent intent = new Intent();
        intent.putExtra(LoongsConfig.member,(Serializable)lists);
        setResult(50,intent);
        finish();
    }

    @Override
    public void onBackPressed() {
        Intent intent = new Intent();
        intent.putExtra(LoongsConfig.member,(Serializable)lists);
        setResult(50,intent);
        finish();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        alertDialog=null;
        EventBus.getDefault().unregister(this);
    }
    @Subscribe (threadMode = ThreadMode.MAIN)
    public void event(Complain complain){
        switch (complain.getType()){
            case QUIT_GROUP:
                break;
            case DELETE_FRIEND:
                break;
            case KICK_MEMBER:
                if (aBoolean)
                deleteMember(index);
                break;
            case NO_QUIT_GROUP:
                break;
        }
    }
    @Override
    protected String getActivityName() {
        return this.getClass().getSimpleName();
    }
}
